<?php

namespace App\Http\Controllers\Admin;

use App\Enums\CriticalEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use App\Traits\AdminLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PersonalPoolUserDetailController extends BaseController
{
    use AdminLog;
    private $model;

    public function __construct()
    {
        $this->model = app('model_personal_pool_user_detail');
    }

    /**
     * @api {Get} personal/user/pool 特殊个人奖池查看用户详情
     *
     * @apiGroup 暴击奖池-特殊个人奖池
     *
     * @apiParam {Int} user_id 用户id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "list": [
    {
    "id": 3,
    "gift_id": 79, 礼物id
    "number": 10, 礼物数量
    "critical_times 暴击数量": 10,
    "type": 1,
    "gift_name": "初恋", 礼物名称
    "price": 334400, 价格
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/ffXwrGW6Bc.png", 图片
    "special": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/BkWinjbkfT.svga",
    "quality": "橙色" 品质
    }
    ],
    "pool_name": "奖池", 奖池名称
     "critical_gift_ids 可以暴击的礼物ids": [
    542,
    543
    ],
    "left": "10", 剩余礼物数量
    "total": "3344000", 剩余礼物总金额
    "user": { 用户信息
    "nickname": "厦雅逸6298878", 昵称
    "user_id": 643775 用户id
    }
    }
    }
     */
    public function detail(Request $request)
    {
        $userId = $request->user_id;

        if (!$userId) {
            throw new BasicException(0, '请选择用户');
        }
        $user = app('model_user_data')->where(['user_id' => $userId])->select('nickname', 'user_id')->first();
        if (!$user) {
            throw new BasicException(0, '用户不存在');
        }
        $list = $this->model->getUserIndependentPoolList($userId);
        $poolName = empty($list)?'':'奖池'.$list[0]['type'];
        $criticalGifts = app('model_critical_prize')->getModuleGiftIds(CriticalEnum::MODULE_TREE);
        $returnData = [
            'critical_gift_ids'  => $criticalGifts,
            'list' => $list,
            'pool_name' => $poolName,
            'left' => $this->model->getUserIndependentPoolCount($userId),
            'total' => $this->model->getUserIndependentPoolTotal($userId),
            'user' => $user,
        ];
        return Response::sendData($returnData);
    }

    /**
     * @api {Post} personal/user/pool 添加用户礼物
     *
     * @apiGroup 暴击奖池-特殊个人奖池
     *
     * @apiParam {Int} user_id 用户id
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} gift_num 礼物数量
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function giftAdd(Request $request)
    {
        $userId = $request->user_id;
        $giftId = $request->gift_id;
        $giftNum = $request->gift_num;

        $this->paramVerify($userId, $giftId, $giftNum);
        $res = $this->model->insert([
            'user_id' => $userId,
            'gift_id' => $giftId,
            'number' => $giftNum,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '新增失败，请联系管理员');
        }
    }

    /**
     * @api {put} personal/user/pool 编辑用户礼物
     *
     * @apiGroup 暴击奖池-特殊个人奖池
     *
     * @apiParam {Int} user_id 用户id
     * @apiParam {String} gift_info 礼物修改信息，格式：id,礼物id,数量。多个用分号;连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function giftEdit(Request $request)
    {
        $userId = $request->user_id;
        $giftInfo = $request->gift_info;

        $ids = $this->model->where('user_id', $userId)->pluck('id')->toArray();

        $giftInfo = explode(';', $giftInfo);

        DB::beginTransaction();
        try {
            $selectedGiftIds = [];
            foreach ($giftInfo as $userGift) {
                if ($userGift) {
                    $userGift = explode(',', $userGift);
                    //id
                    if (isset($userGift[0])) {
                        $id = $userGift[0];
                        if (!in_array($id, $ids)) throw new BasicException(10001);
                    } else throw new BasicException(10001);
                    //礼物id
                    if (isset($userGift[1])) {
                        $giftId = $userGift[1];
                        $selectedGiftIds[] = $giftId;
                    } else throw new BasicException(10001);
                    //礼物数量
                    if (isset($userGift[2])) {
                        $giftNum = $userGift[2];
                    } else throw new BasicException(10001);

                    $this->paramVerify($userId, $giftId, $giftNum, $id);

                    $this->model->where('id', $id)->update(['gift_id' => $giftId, 'number' => $giftNum]);
                }
            }
            //批量修改的时候是否选择了重复礼物
            if (count($selectedGiftIds) != count(array_unique($selectedGiftIds))) throw new BasicException(0, '礼物重复');

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    private function paramVerify($userId, $giftId, $giftNum, $id = 0)
    {
        $user = app('model_user')->where('user_id', $userId)->where('deleted', 0)->value('user_id');
        if (empty($user)) throw new BasicException(0, '用户不存在');

        if (empty($giftId)) throw new BasicException(0, '请选择礼物');

        $where = [
            'id' => $giftId,
            'type' => 2,
        ];
        if(empty($id)){
            $where['sold'] = 1;
        }
        $gift = app('model_gift')->where($where)->value('id');
        if (empty($gift)) throw new BasicException(10001,'礼物不存在或已下架或不在可设置列表');

        $exist = $this->model->where(['user_id' => $userId, 'gift_id' => $giftId])
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })->value('id');
        if ($exist) throw new BasicException(0, '礼物已经存在');

        if (empty($giftNum) || !is_numeric($giftNum) || $giftNum < 0) throw new BasicException(10001);
    }

    /**
     * @api {Delete} personal/user/pool  删除用户礼物
     *
     * @apiGroup 暴击奖池-特殊个人奖池
     *
     * @apiParam {String} ids 要删除的id，多个用英文逗号,连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function giftDel(Request $request)
    {
        $ids = $request->ids;

        $ids = str_replace('"', '', $ids);
        $ids = str_replace('\'', '', $ids);
        $ids = str_replace(' ', '', $ids);
        $ids = explode(',', $ids);

        //更新
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id) {
                    $exist = $this->model->where('id', $id)->value('id');
                    if ($exist) $this->model->where('id', $id)->delete();
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }
}